/**
 * Description：理化试验申请 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.8.13
 */
const { ref, reactive } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus
import { useCommon } from '../useCommon.js';

export function useEntrustMetering() {
  const baseAPI = '../../../Ashx/EntrustMeteringVue3PageHandler.ashx';
  const entrustMeteringObj = reactive({
    dialogVisible: false,
    tabIndex: 'first',
    // 表单
    form: {
      containername: '',
      containerid: '',
      productid: '',
      productname: '',
      productdesc: '',
      workflowstepname: '',
      workflowstepid: '',
      originalfactoryname: '',//委托单位
      qty: '',//
      entrustMeteringCheckName: '',//委托单号
      entrustMeteringQty: 0,//委托数量
      entrustMeteringedQty: 0,//已委托数量
      workreportnum: 0,//已报工数
      requireGetDate: '',//要求取件日期
      reserveGetDate: '', //预定取件日期
      specification: '',//材料标准或规范
      batchNO: '',//炉批号
      checktype: '3',//检验类型
      remark: '',//委托备注
    },
    dataList: [],
    // 检测项维护表单
    checkItemMaintForm: {
      CheckName: '',//检测项目
      CheckDesc: '',//检测项描述
      DrawingNO: '',//图纸序号
    },
    inputConfig: {
      entrustMeteringQtyDisable: false,
    },
    // 表单校验
    formRules: {
      requireGetDate: [
        { required: true, message: '【要求取件日期】不能为空', trigger: 'blur' }
      ],
      reserveGetDate: [
        { required: true, message: '【预定取件日期】不能为空', trigger: 'blur' }
      ],
      specification: [
        { required: true, message: '【材料标准或规范】不能为空', trigger: 'blur' }
      ],
      batchNO: [
        { required: true, message: '【炉批号】不能为空', trigger: 'blur' }
      ],
      remark: [
        { required: true, message: '【委托备注】不能为空', trigger: 'blur' }
      ]
    }
  });

  // 检测项目
  const options = [
    {
      label: '金相专业',
      options: [
        { value: '金相检查' },
        { value: '显微组织' },
        { value: '显微硬度' },
        { value: '晶粒度' },
        { value: '高倍' },
        { value: '低倍' }
      ]
    },
    {
      label: '化学专业',
      options: [
        { value: '化学分析' },
        { value: '气体分析' },
        { value: '试车气体分析' }
      ]
    },
    {
      label: '力学专业',
      options: [
        { value: '组合持久' },
        { value: '高温持久' },
        { value: '高温拉伸' },
        { value: '高温蠕变' },
        { value: '焊接拉力' },
        { value: '室温拉伸' },
        { value: '室温冲击' },
        { value: '硬度' },
        { value: '弯曲' },
        { value: '热稳定' },
        { value: '热震' },
        { value: '涂层结合力强度' }
      ]
    },
    {
      label: '非金相专业',
      options: [
        { value: '附着力' },
        { value: '颗粒度' },
        { value: '油料光谱' },
        { value: '闪点' },
        { value: '粘度' },
        { value: '杂质' },
        { value: '密度' }
      ]
    }
  ];

  const entrustMeteringTableRef = ref(null);//检测项表格ref
  const entrustMeteringFormRef = ref(null);//表单ref
  const entrustMeteringCheckItemMaintFormRef = ref(null);//检测项维护表单ref
  const { generateUUID } = useCommon();
  let currentUserInfo = {};// 当前登录用户信息

  // 查询委托单号
  async function getEntrustMeteringNo(employeename) {
    const { data } = await useFetch({
      url: `${baseAPI}?actions=getEntrustMeteringNo`,
      data: { type: 'getEntrustMeteringNo', employeename }
    });
    return data.value;
  }

  // 查询已委托数
  async function getEntrustMeteringedQty(containerid, workflowstepid) {
    const { data } = await useFetch({
      url: `${baseAPI}?actions=getEntrustMeteringedQty`,
      data: { type: 'getEntrustMeteringedQty', containerid, workflowstepid }
    });
    return data.value;
  }

  // 初始化数据
  async function initEntrustMeteringDialogData(currentSelectContainer, selectionRows, userInfo) {
    entrustMeteringObj.dialogVisible = true;
    currentUserInfo = userInfo.value;
    const { workflowstepname, productid, productname, productdescription, workflowstepid } = currentSelectContainer;
    const { containername, qty, originalfactoryname, workreportnum, containerid } = selectionRows[0];
    const entrustMeteringNo = await getEntrustMeteringNo(userInfo.value.employeename);//获取委托单号
    const entrustMeteringedQty = await getEntrustMeteringedQty(containerid, workflowstepid);//查询已委托数
    entrustMeteringObj.form.containerid = containerid;
    entrustMeteringObj.form.containername = containername;
    entrustMeteringObj.form.productname = productname;
    entrustMeteringObj.form.productid = productid;
    entrustMeteringObj.form.productdesc = productdescription;
    entrustMeteringObj.form.workflowstepid = workflowstepid;
    entrustMeteringObj.form.workflowstepname = workflowstepname;
    entrustMeteringObj.form.originalfactoryname = originalfactoryname;
    entrustMeteringObj.form.qty = qty;//批次在制数
    entrustMeteringObj.form.entrustMeteringCheckName = entrustMeteringNo;
    entrustMeteringObj.form.entrustMeteringedQty = parseInt(entrustMeteringedQty);
    entrustMeteringObj.form.entrustMeteringQty = 1;//委托数量
    entrustMeteringObj.form.workreportnum = workreportnum;//已报工数

    if (qty === 1) {
      entrustMeteringObj.inputConfig.entrustMeteringQtyDisable = true;
    }
  }

  // 重置对话框数据
  function resetDialogData() {
    entrustMeteringObj.dataList = [];
    entrustMeteringFormRef.value.resetFields();//重置表单校验
    entrustMeteringCheckItemMaintFormRef.value.resetFields();//重置检测项维护表单
  }

  // 【提交】按钮点击
  async function handleEntrustMeteringSubmit() {
    // 其他校验
    if (!await validate()) { return; }

    ElMessageBox.confirm(`你确认要提交吗?`, '确认', { type: 'warning' }).then(async () => {
      const selection = entrustMeteringTableRef.value.getSelectionRows();
      const { data } = await useFetch({
        url: `${baseAPI}?actions=saveData`,
        data: {
          type: 'saveData',
          employeename: currentUserInfo.employeename,
          ...entrustMeteringObj.form,
          checkItemList: selection
        }
      });
      if (data.value === true) {
        ElMessage({ type: 'success', message: `保存成功`, grouping: true });
        entrustMeteringObj.dialogVisible = false;
        resetDialogData();
      } else {
        ElMessage({ type: 'error', message: `保存失败`, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  async function validate() {
    // 表单校验
    try {
      await entrustMeteringFormRef.value.validate();
    } catch (error) {
      ElMessage({ type: 'error', message: `必填字段不能为空`, grouping: true });
      return false;
    }

    if (entrustMeteringObj.dataList.length === 0) {
      ElMessage({ type: 'error', message: `请先添加检测项`, grouping: true });
      return false;
    }

    const selection = entrustMeteringTableRef.value.getSelectionRows();
    if (selection.length == 0) {
      ElMessage({ type: 'error', message: `请勾选检测项`, grouping: true });
      return false;
    }

    return true;
  }

  // 获取检测项内容
  function getCheckItemValue() {
    const iframe = document.getElementById('pointContent');
    const elementInIframe = iframe.contentDocument.getElementById('wucToleranceInput1_ftbFinalHtml_designEditor');
    const innerHTML = elementInIframe.contentDocument.body.innerHTML;
    return innerHTML ? innerHTML.replace(/img/g, "IMG") : '';
  }

  // 清空检测项内容
  function clearCheckItemValue() {
    const iframe = document.getElementById('pointContent');
    const elementInIframe = iframe.contentDocument.getElementById('wucToleranceInput1_ftbFinalHtml_designEditor');
    elementInIframe.contentDocument.body.innerHTML = "";
  }

  // 添加按钮
  function handleEntrustMeteringAddClick() {
    const checktype = entrustMeteringObj.form.checktype;
    let checkitem = checktype !== '3' ? getCheckItemValue() : entrustMeteringObj.checkItemMaintForm.CheckName;//检测项目
    if (!checkitem) {
      return ElMessage({ type: 'error', message: `${checktype !== '3' ? '【检测项内容】' : '【检测项目】'}不能为空`, grouping: true });
    }
    if (!entrustMeteringObj.checkItemMaintForm.CheckDesc) { return ElMessage({ type: 'error', message: `请填写【检测项描述】`, grouping: true }); }
    if (checktype !== '3' && !entrustMeteringObj.checkItemMaintForm.DrawingNO) {
      return ElMessage({ type: 'error', message: `请填写【图纸序号】`, grouping: true });
    }

    entrustMeteringObj.dataList.push({
      id: generateUUID(),
      StrSize: checkitem,//要求尺寸、检测项目
      CheckDesc: entrustMeteringObj.checkItemMaintForm.CheckDesc,//检测项描述
      DrawingNO: checktype === '3' ? '' : entrustMeteringObj.checkItemMaintForm.DrawingNO,//图纸序号
    });

    if (checktype !== '3') {
      clearCheckItemValue();//清空检测内容
    }

    entrustMeteringTableRef.value.toggleAllSelection();//勾选已有全部检测项
    entrustMeteringCheckItemMaintFormRef.value.resetFields();//重置检测项维护表单
  }

  // 删除按钮
  function handleEntrustMeteringDeleteClick() {
    const selection = entrustMeteringTableRef.value.getSelectionRows();
    if (selection.length === 0) { return ElMessage({ type: 'error', message: `请勾选要删除的数据`, grouping: true }); }
    entrustMeteringObj.dataList = entrustMeteringObj.dataList.filter(i => !selection.some(m => m.id === i.id));
  }

  // 【委托数量】blur事件
  function handleEntrustMeteringQtyBlur() {
    const {
      workreportnum,//已报工数
      entrustMeteringQty,//委托数量
      entrustMeteringedQty,//已委托数量
    } = entrustMeteringObj.form;
    const reg = /^[1-9]\d*$/;//正整数正则
    if (!reg.test(entrustMeteringQty)) {
      entrustMeteringObj.form.entrustMeteringQty = 1;
      return ElMessage({ type: 'error', message: `【委托数量】必须是正整数`, grouping: true });
    }
    if (parseInt(entrustMeteringQty) + parseInt(entrustMeteringedQty) > parseInt(workreportnum)) {
      entrustMeteringObj.form.entrustMeteringQty = 1;
      return ElMessage({ type: 'error', message: `【委托数量】不能大于【已报工数量】`, grouping: true });
    }
  }

  //【委托类型】change事件
  function handleEntrustMeteringChecktypeChange() {
    entrustMeteringObj.dataList = [];
    entrustMeteringCheckItemMaintFormRef.value.resetFields();//重置检测项维护表单
  }

  return {
    entrustMeteringObj,
    entrustMeteringTableRef,
    entrustMeteringFormRef,//表单ref
    entrustMeteringCheckItemMaintFormRef,//检测项维护表单ref
    initEntrustMeteringDialogData,
    options, //检测项目
    handleEntrustMeteringSubmit,//提交按钮点击
    handleEntrustMeteringAddClick,//添加按钮点击事件
    handleEntrustMeteringDeleteClick,//删除按钮点击事件
    handleEntrustMeteringQtyBlur,//【委托数量】blur事件
    handleEntrustMeteringChecktypeChange,//【委托类型】change事件
  };
}